package city.spring.modules.health.service.impl;

import city.spring.modules.health.entity.DiseaseEntity;
import city.spring.modules.health.repository.DiseaseRepository;
import city.spring.modules.health.service.DiseaseService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Service：疾病信息表
 *
 * @author 侯坤林
 * @date 2020-07-07 10:20:49
 */
@CacheConfig(cacheNames = {DiseaseServiceImpl.CACHE_NAME})
@Transactional(rollbackFor = Throwable.class)
@Service
public class DiseaseServiceImpl extends ServiceImpl<DiseaseRepository, DiseaseEntity> implements DiseaseService {

    @Override
    public void saveDisease(DiseaseEntity entity) {
        checkDuplicate(entity);
        if (!save(entity)) {
            throw new RuntimeException("保存信息失败");
        }
    }

    @Override
    public void updateDisease(DiseaseEntity entity) {
        // 使用 updateById(entity); 修改数据时，将会修改 entity 对象中所有非null数据，如果某个字段为null，将会忽略该字段的修改
        checkDuplicate(entity);
        boolean update = updateById(entity);
        if (!update) {
            throw new RuntimeException("修改信息失败");
        }
    }

    /**
     * 检查疾病信息是否重复
     *
     * @param entity 疾病信息
     */
    private void checkDuplicate(DiseaseEntity entity) {
        long count = lambdaQuery()
                .eq(DiseaseEntity::getTitle, entity.getTitle())
                .ne(DiseaseEntity::getId, entity.getId())
                .count();
        if (count > 0) {
            throw new RuntimeException("系统中已经存在该疾病信息，请勿重复添加");
        }
    }

    @Override
    public void deleteDisease(String primaryKey) {
        removeById(primaryKey);
    }

    @Override
    public void deleteDisease(List<String> primaryKeys) {
        removeByIds(primaryKeys);
    }

    @Override
    public List<DiseaseEntity> getFoodDisease(String foodInfoId, int forbiddenOrRecommend) {
        return baseMapper.getFoodDisease(foodInfoId, forbiddenOrRecommend);
    }

    @Override
    public List<DiseaseEntity> getRecipesDisease(String recipesId) {
        return baseMapper.getRecipesDisease(recipesId);
    }

    @Override
    public List<DiseaseEntity> getFoodDiseaseAll(String foodInfoId) {
        return baseMapper.getFoodDiseaseAll(foodInfoId);
    }

}
